/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Dao.AlunoDao;
import Dao.AlunoDaoImplJPA;
import Dao.HistoricoDao;
import Dao.HistoricoDaoImplJPA;
import Dao.HistoricoTurmaDao;
import Dao.HistoricoTurmaDaoImplJPA;
import Pojo.Aluno;
import Pojo.Historico;
import Pojo.HistoricoTurma;
import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
/**
 *
 * @author thiago
 */
public class FormCadastroAlunos extends javax.swing.JInternalFrame {

    /** String de modificação N = novo, A = alteração*/
    String modificacao;

    /**
     * Setter de modificação
     * @param modificacao 
     */
    public void setModificacao(String modificacao) {
        this.modificacao = modificacao;
    }

    /**
     * Getter de modificação
     * @return 
     */
    public String getModificacao() {
        return modificacao;
    }
    
    /**
     * Creates new form FormCadastroAlunos
     */
    public FormCadastroAlunos() {
        initComponents();
    }
    
    /**
     * Creates new form FormCadastroAlunos
     */
    public FormCadastroAlunos(int id) {
        initComponents();
        txtCodigo.setText(String.valueOf(id));
        this.carregarDadosCampos(id);
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtCpf = new javax.swing.JTextField();
        lblCpf = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        lblNome = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        lblCodigo = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Cadastro de Alunos");

        txtCpf.setEnabled(false);

        lblCpf.setText("CPF");

        txtNome.setEnabled(false);

        lblNome.setText("Nome");

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
        });

        lblCodigo.setText("Código");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtNome)
                    .addComponent(txtCpf)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblNome)
                            .addComponent(lblCpf)
                            .addComponent(lblCodigo)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 86, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblCodigo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(lblNome)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(lblCpf)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.setEnabled(false);
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnRemover.setText("Remover");
        btnRemover.setEnabled(false);
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.setEnabled(false);
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setEnabled(false);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnNovo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAlterar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnRemover)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void carregarDadosCampos(int codigo){
        AlunoDao alunoDao = new AlunoDaoImplJPA();
        Aluno aluno = alunoDao.pesquisarPorId(codigo);

        if (aluno != null){
            txtNome.setText(aluno.getNome());
            txtCpf.setText(aluno.getCpf());

            btnNovo.setEnabled(true);
            btnAlterar.setEnabled(true);
            btnRemover.setEnabled(true);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);
        } else {
            txtNome.setText("");
            txtCpf.setText("");

            btnNovo.setEnabled(true);
            btnAlterar.setEnabled(false);
            btnRemover.setEnabled(false);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);
            JOptionPane.showMessageDialog(null, "Não existe um aluno com esse código.");
        }
    }
    
    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        
        txtCodigo.setEnabled(false);
        txtNome.setEnabled(true);
        txtCpf.setEnabled(true);
        
        txtNome.setText("");
        txtCpf.setText("");
        
        btnNovo.setEnabled(false);
        btnAlterar.setEnabled(false);
        btnRemover.setEnabled(false);
        btnSalvar.setEnabled(true);
        btnCancelar.setEnabled(true);
        
        txtNome.grabFocus();
        this.setModificacao("N");
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (txtCodigo.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe um aluno para ser alterado.");
        }else{
            txtCodigo.setEnabled(false);
            txtNome.setEnabled(true);
            txtCpf.setEnabled(true);

            btnNovo.setEnabled(false);
            btnAlterar.setEnabled(false);
            btnRemover.setEnabled(false);
            btnSalvar.setEnabled(true);
            btnCancelar.setEnabled(true);

            txtNome.grabFocus();
            this.setModificacao("A");
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        if (txtCodigo.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe um aluno para ser removido.");
        }else{
            if (JOptionPane.showConfirmDialog(null, "Deseja remover o aluno?")==0){
                
                //gerando o codigo do aluno
                Aluno aluno = new Aluno(Integer.parseInt(txtCodigo.getText()),txtNome.getText(),txtCpf.getText());
                AlunoDao alunoDao = new AlunoDaoImplJPA();
                
                HistoricoDao historicoDao = new HistoricoDaoImplJPA();
                List<Historico> listaHistoricoAluno = historicoDao.pesquisarPorAluno(aluno);
                if (listaHistoricoAluno.isEmpty()){
                    JOptionPane.showMessageDialog(null, "Não é possível excluir esse aluno, pois este já cursou matérias.");
                    return;
                }
                
                HistoricoTurmaDao historicoTurmaDao = new HistoricoTurmaDaoImplJPA();
                List<HistoricoTurma> listaHistoricoTurmaAluno = historicoTurmaDao.pesquisarPorAluno(aluno);
                if (listaHistoricoTurmaAluno.isEmpty()){
                    JOptionPane.showMessageDialog(null, "Não é possível excluir esse aluno, pois este já foi matriculado em alguma turma.");
                    return;
                }
                
                if (alunoDao.remover(aluno)==true){
                
                    txtCodigo.setEnabled(true);
                    txtNome.setEnabled(false);
                    txtCpf.setEnabled(false);

                    txtCodigo.setText("");
                    txtNome.setText("");
                    txtCpf.setText("");

                    btnNovo.setEnabled(true);
                    btnAlterar.setEnabled(false);
                    btnRemover.setEnabled(false);
                    btnSalvar.setEnabled(false);
                    btnCancelar.setEnabled(false);
                    
                    JOptionPane.showMessageDialog(null, "Aluno removido com sucesso.");
                }else{
                    JOptionPane.showMessageDialog(null, "Erro ao remover o aluno.");
                }
            }
        }
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        
        AlunoDao alunoDao = new AlunoDaoImplJPA();
        Aluno aluno;
        boolean salvo = false;
               
        if (txtNome.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe o nome do Aluno.");
            return;
        }
        
        if (txtCpf.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe o cpf do Aluno.");
            return;
        }
        
        if (this.getModificacao().equals("A")){
            aluno = new Aluno(Integer.parseInt(txtCodigo.getText()),txtNome.getText(),txtCpf.getText());
            if (alunoDao.alterar(aluno)==true){
                JOptionPane.showMessageDialog(null, "Aluno alterado com sucesso.");
                salvo = true;
            }else{
                JOptionPane.showMessageDialog(null, "Erro ao alterar o aluno.");
                salvo = false;
            }
        }else if (this.getModificacao().equals("N")){
            aluno = new Aluno(txtNome.getText(),txtCpf.getText());

            if (alunoDao.inserir(aluno)==true){
                JOptionPane.showMessageDialog(null, "Aluno inserido com sucesso.");
                salvo = true;
            }else{
                JOptionPane.showMessageDialog(null, "Erro ao inserir o aluno.");
                salvo = false;
            }
        }
        
        if (salvo == true){
            txtCodigo.setEnabled(true);
            txtNome.setEnabled(false);
            txtCpf.setEnabled(false);

            txtCodigo.setText("");
            txtNome.setText("");
            txtCpf.setText("");

            btnNovo.setEnabled(true);
            btnAlterar.setEnabled(false);
            btnRemover.setEnabled(false);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);
            
            this.setModificacao("");
            
            txtCodigo.grabFocus();
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        txtCodigo.setEnabled(true);
        txtNome.setEnabled(false);
        txtCpf.setEnabled(false);

        txtCodigo.setText("");
        txtNome.setText("");
        txtCpf.setText("");

        btnNovo.setEnabled(true);
        btnAlterar.setEnabled(false);
        btnRemover.setEnabled(false);
        btnSalvar.setEnabled(false);
        btnCancelar.setEnabled(false);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        if (evt.getKeyCode()==10){
            int codigo;
            try{
                codigo = Integer.parseInt(txtCodigo.getText());
            }catch(Exception e){
                return;
            }
            this.carregarDadosCampos(codigo);
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnRemover;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblCpf;
    private javax.swing.JLabel lblNome;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtCpf;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables
}
